/**
 * Created by Luo jiaxing 2017/7/26 0025.
 */

$(function () {
    var table = new tableFactory();
    addListeners(table);
});

function tableFactory() {
    var me = this;
    me.enabled = null;
    me.data = null;
    me.userRoleData = null;
    me.roleData = null;
    me.deptData = null;
    var init = function () {
        $.when(loadDeptData(me)).then(function () {
            $("#user").bootstrapTable({
                method: 'get',					  //请求方式（*）
                striped: true,					  //是否显示行间隔色
                cache: false,					   //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                pagination: true,				   //是否显示分页（*）
                sortable: true,					 //是否启用排序
                sortOrder: "asc",				   //排序方式
                sidePagination: "client",		   //分页方式：client客户端分页，server服务端分页（*）
                pageNumber: 1,					   //初始化加载第一页，默认第一页
                search: true,					   //是否显示表格搜索，只能进行客户端搜索
                strictSearch: false,                //true为全匹配，false为模糊查询
                showColumns: false,				  //是否显示筛选列按钮
                showRefresh: false,				  //是否显示刷新按钮
                clickToSelect: true,				//是否启用点击选中行
                showToggle: false,					//是否显示详细视图和列表视图的切换按钮
                cardView: false,					//是否显示详细视图
                detailView: false,				   //是否显示父子表
                singleSelect: true,
                height: 'auto',
                pageSize: 10,
                pageList: [10, 25, 50, 100],
                columns: [{
                    field: 'check', checkbox: false
                }, {
                    title: '所属部门', field: 'deptname', align: 'center',
                    formatter: function (value, row, index) {
                        return me.getDeptName(row.departmentid);
                    }
                }, {
                    title: '登录账号', field: 'loginname', align: 'center'
                }, {
                    title: '真实姓名', field: 'realname', align: 'center'
                }, {
                    title: '登录密码', field: 'loginpassword', align: 'center'
                }, {
                    title: '电话', field: 'phone', align: 'center'
                }, {
                    title: '头衔', field: 'title', align: 'center'
                }, {
                    title: '性别', field: 'sex', align: 'center',
                    formatter: function (value) {
                        return value === 1 ? '男' : (value === 0 ? '女' : '');
                    }
                }, {
                    title: 'QQ', field: 'qq', align: 'center'
                }, {
                    title: '序号', field: 'ordernum', align: 'center'
                }, {
                    title: '微信ID', field: 'weixinid', align: 'center'
                }, {
                    title: '微信名称', field: 'weixinname', align: 'center'
                }, {
                    title: '备注', field: 'remark', align: 'center'
                },{
                    title: '角色', field: 'rolename', align: 'center',
                    formatter: function (value, row, index) {
                        return me.getUserRoleByUserId(row.userid);
                    }
                },  {
                    title: '操作', field: '', align: 'center', width: 250,
                    formatter: function (value, row) {
                        var html = [];
                        var isChecked = row.enabled ? 'checked' : '';
                        html.push('<button class="btn btn-default btn-xs" style="margin-right: 10px;">');
                        html.push('<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> 修改密码</button>');
                        html.push('<button class="btn btn-primary btn-xs" style="display: none;"></button>');
                        html.push('<input class="enabled-btn-switch" type="checkbox" ' + isChecked + ' />');
                        return html.join('');
                    },
                    events: {
                        'click .btn-default': function (e, value, row, index) {
                            new changePWModalFactory(row.userid, me);
                        },
                        'click .btn-primary': function (e, value, row, index) {
                            setTimeout(function () {
                                me.enableUser(row.userid);
                            }, 500);
                        }
                    }
                }]
            });
            me.loadData();
        });
    };
    init();
}

tableFactory.prototype = {
    //获取用户数据
    loadData: function () {
        var me = this;
        $.when(me.loadUserRoleData()).then(function () {
            $.getJSON('../userManage/selectAll', '', function (_data) {
                me.data = _data;
                $("#user").bootstrapTable("load", _data);
                me.initSwitchBtn();
            });
        });
    },
    //加载用户角色数据
    loadUserRoleData: function () {
        var def = $.Deferred();
        var me = this;
        $.getJSON('../userRoleManage/selectAll', '', function (_data) {
            me.userRoleData = _data;
            def.resolve();
        });
        return def.promise();
    },
    //获取用户角色表中角色ID,传进来的是用户ID
    getUserRoleByUserId: function (userId) {
        var roleId;
        var me = this;
        $.each(this.userRoleData, function (index, item) {
            if (item.userid === userId) {
                roleId = item.roleid;
                return false;
            }
        });
        return  me.getRoleByRoleId(roleId);
    },
    //获取角色表数据
    loadRoleData: function () {
        var def = $.Deferred();
        var me = this;
        $.getJSON('../roleManage/selectAll', '', function (_data) {
            me.roleData = _data;
            def.resolve();
        });
        return def.promise();
    },
    //根据角色Id得到角色名称
    getRoleByRoleId: function (roleId) {
        var roleName = '';
        $.each(this.roleData, function (index, item) {
            if (item.roleid === roleId) {
                roleName = item.rolename;
                return false;
            }
        });
        return roleName;
    },



    initSwitchBtn: function () {
        var me = this;
        $('.enabled-btn-switch').bootstrapSwitch({
            size: 'mini',
            onText: '启用',
            offText: '未启用',
            onColor: 'success',
            offColor: 'danger'
        });
        $('.enabled-btn-switch').on('switchChange.bootstrapSwitch', function (event, state) {
            me.enabled = state;
            $(this).parent().parent().parent().find('.btn-primary').trigger('click');
        });
    },
    enableUser: function (_userid) {
        var me = this;
        var obj = {
            userid: _userid,
            enabled: this.enabled
        };
        $.post("../userManage/updateEnabled", obj, function (data) {
            if (data === 'true') {
                me.loadData();
                layer.msg("更新成功！", {icon: 1});
            } else {
                layer.msg("更新失败！", {icon: 2});
            }
        });
    },
    getDeptName: function (id) {
        var name = '';
        id = parseInt(id);
        $.each(this.deptData, function (index, item) {
            if (item.departmentid === id) {
                name = item.deptname;
                return false;
            }
        });
        return name;
    }
};
//加载部门表中的数据
function loadDeptData (_this) {
    var def = $.Deferred();
    $.getJSON('../departmentManage/selectAll', '', function (_data) {
        _this.deptData = _data;
        def.resolve();
    });
    return def.promise();
}

function changePWModalFactory (userid, linkTable) {
    var me = this;
    me.userid = userid;
    me.index = null;
    me.linkTable = linkTable;
    me.init = function () {
        var html = [];
        html.push('<div style="margin: 10px 20px;"><form class="form-horizontal" id="password-from">');
        html.push('<div class="form-group">');
        html.push('<label for="user-loginpassword" class="col-sm-3 control-label"><span style="color: #FF0000;">* </span>密码:</label>');
        html.push('<div class="col-sm-9"><input type="password" name="password" class="form-control" id="user-loginpassword"></div>');
        html.push('</div>');
        html.push('<div class="form-group">');
        html.push('<label for="user-confirmpw" class="col-sm-3 control-label"><span style="color: #FF0000;">* </span>确认密码:</label>');
        html.push('<div class="col-sm-9"><input type="password" name="confirm_password" class="form-control" id="user-confirmpw"></div>');
        html.push('</div>');
        html.push('<div class="form-group" style="display: none;"><input class="submit" type="submit" value="submit"></div>');
        html.push('</from></div>');
        me.index = layer.open({
            type: 1, area: '450px', title: '修改密码', btn: ['确定'],
            content: html.join(''),
            success: function () {
                $("#password-from").validate({
                    rules: {
                        password: {
                            required: true,
                            minlength: 5
                        },
                        confirm_password: {
                            required: true,
                            minlength: 5,
                            equalTo: "#user-loginpassword"
                        }
                    },
                    messages: {
                        password: {
                            required: '请输入密码',
                            minlength: '密码长度不能小于 5 个字符'
                        },
                        confirm_password: {
                            required: '请再次输入密码',
                            minlength: '密码长度不能小于 5 个字符',
                            equalTo: '两次密码输入不一致'
                        }
                    },
                    submitHandler: function () {
                        me.update();
                    }
                });
            },
            yes: function () {
                $('#password-from .submit').trigger('click');
            }
        });
    };
    me.update = function () {
        var obj = {
            userid: me.userid,
            loginpassword: md5($('#user-loginpassword').val())
        };
        $.post("../userManage/updatePassword", obj, function (data) {
            if (data === 'true') {
                layer.close(me.index);
                me.linkTable.loadData();
                layer.msg("更新密码成功！", {icon: 1});
            } else {
                layer.msg("更新密码失败！", {icon: 2});
            }
        });
    };
    me.init();
}

function modalFactory (_type, _tableObj) {
    var me = this;
    var select = $("#user").bootstrapTable('getSelections');
    if (_type === 'edit' && select.length !== 1) {
        layer.msg('请选择需要修改的用户', {icon: 0});
        return;
    }
    me.type = _type;
    me.title = _type === 'add' ? '添加用户': (_type === 'edit' ? '修改用户': '');
    me.index = null;
    me.linkTable = _tableObj;
    me.editUserId = null;
    me.userRoleData = _tableObj.userRoleData;
    me.deptData = _tableObj.deptData;
    me.roleData = null;
    var getModalContentHTML = function () {
        var html = [];
        html.push('<div style="margin: 10px 20px;"><form class="form-horizontal" id="user-from">');
        html.push('<div class="form-group">');
        html.push('<label for="user-loginname" class="col-sm-3 control-label"><span style="color: #FF0000;">* </span>登录名称:</label>');
        html.push('<div class="col-sm-9"><input type="text" name="loginname" class="form-control" id="user-loginname"></div>');
        html.push('</div>');
        if (me.type === 'add') {
            html.push('<div class="form-group">');
            html.push('<label for="user-loginpassword" class="col-sm-3 control-label"><span style="color: #FF0000;">* </span>密码:</label>');
            html.push('<div class="col-sm-9"><input type="password" name="password" class="form-control" id="user-loginpassword"></div>');
            html.push('</div>');
            html.push('<div class="form-group">');
            html.push('<label for="user-confirmpw" class="col-sm-3 control-label"><span style="color: #FF0000;">* </span>确认密码:</label>');
            html.push('<div class="col-sm-9"><input type="password" name="confirm_password" class="form-control" id="user-confirmpw"></div>');
            html.push('</div>');
        }
        html.push('<div class="form-group">');
        html.push('<label for="user-realname" class="col-sm-3 control-label">真实姓名:</label>');
        html.push('<div class="col-sm-9"><input type="text" class="form-control" id="user-realname"></div>');
        html.push('</div>');
        html.push('<div class="form-group">');
        html.push('<label for="user-departmentid" class="col-sm-3 control-label">角色:</label>');
        html.push('<div class="col-sm-9"><select class="form-control" id="user-roleid">');
        $.each(me.roleData, function (index, item) {
            html.push('<option value="' + item.roleid + '">' + item.rolename + '</option>');
        });
        html.push('</select></div></div>');
        html.push('<div class="form-group">');
        html.push('<label for="user-departmentid" class="col-sm-3 control-label">所属部门:</label>');
        html.push('<div class="col-sm-9"><select class="form-control" id="user-departmentid">');
        $.each(me.deptData, function (index, item) {
            html.push('<option value="' + item.departmentid + '">' + item.deptname + '</option>');
        });
        html.push('</select></div></div>');
        html.push('<div class="form-group">');
        html.push('<label for="user-title" class="col-sm-3 control-label">头衔:</label>');
        html.push('<div class="col-sm-9"><input type="text" class="form-control" id="user-title"></div>');
        html.push('</div>');
        html.push('<div class="form-group">');
        html.push('<label for="user-sex" class="col-sm-3 control-label">性别:</label>');
        html.push('<div class="col-sm-9"><select class="form-control" id="user-sex">');
        html.push('<option value="1">男</option><option value="2">女</option></select></div>');
        html.push('</div>');
        html.push('<div class="form-group">');
        html.push('<label for="user-phone" class="col-sm-3 control-label">电话:</label>');
        html.push('<div class="col-sm-9"><input type="text" name="phone" class="form-control" id="user-phone"></div>');
        html.push('</div>');
        html.push('<div class="form-group">');
        html.push('<label for="user-qq" class="col-sm-3 control-label">QQ:</label>');
        html.push('<div class="col-sm-9"><input type="text" name="qq" class="form-control" id="user-qq"></div>');
        html.push('</div>');
        html.push('<div class="form-group">');
        html.push('<label for="user-weixinid" class="col-sm-3 control-label">微信号:</label>');
        html.push('<div class="col-sm-9"><input type="text" class="form-control" id="user-weixinid"></div>');
        html.push('</div>');
        html.push('<div class="form-group">');
        html.push('<label for="user-weixinname" class="col-sm-3 control-label">微信名:</label>');
        html.push('<div class="col-sm-9"><input type="text" class="form-control" id="user-weixinname"></div>');
        html.push('</div>');
        html.push('<div class="form-group">');
        html.push('<label for="user-remark" class="col-sm-3 control-label">备注:</label>');
        html.push('<div class="col-sm-9"><input type="text" class="form-control" id="user-remark"></div>');
        html.push('</div>');
        html.push('<div class="form-group" style="display: none;"><input class="submit" type="submit" value="submit"></div>');
        html.push('</form></div>');
        return html.join('');
    };
    var validate = function () {
        // 检测手机号是否正确
        jQuery.validator.addMethod("isMobile", function (value, element) {
            var length = value.length;
            var regPhone = /^1([3578]\d|4[57])\d{8}$/;
            return this.optional(element) || ( length == 11 && regPhone.test(value) );
        });
        // 检测QQ号是否正确
        jQuery.validator.addMethod("isQQ", function (value, element) {
            var regQQ = /[1-9][0-9]{4,}/;
            return this.optional(element) || regQQ.test(value);
        });
        $("#user-from").validate({
            rules: {
                loginname: {
                    required: true,
                    minlength: 1
                },
                password: {
                    required: true,
                    minlength: 5
                },
                confirm_password: {
                    required: true,
                    minlength: 5,
                    equalTo: "#user-loginpassword"
                },
                phone: {
                    required: false,
                    isMobile: true
                },
                qq: {
                    required: false,
                    isQQ: true
                }
            },
            messages: {
                loginname: {
                    required: '请输入登录名',
                    minlength: '用户名至少一个字符'
                },
                password: {
                    required: '请输入密码',
                    minlength: '密码长度不能小于 5 个字符'
                },
                confirm_password: {
                    required: '请再次输入密码',
                    minlength: '密码长度不能小于 5 个字符',
                    equalTo: '两次密码输入不一致'
                },
                phone: {
                    isMobile: '请输入正确的手机号'
                },
                qq: {
                    isQQ: '请输入正确的QQ号'
                }
            },
            submitHandler: function() {
                if (me.type === 'add') {
                    me.save();
                } else if (me.type === 'edit') {
                    me.update();
                }
            }
        });
    };
    var getUserRoles = function () {
        var def = $.Deferred();
        $.getJSON('../roleManage/getRoles', function (_data) {
            me.roleData = _data;
            def.resolve();
        });
        return def.promise();
    };
    var init = function (getModalContentHTML, getUserRoles, validate) {
        $.when(getUserRoles()).then(function () {
            me.index = layer.open({
                type: 1, area: ['500px', '400px'], title: me.title, btn: ['确定'],
                content: getModalContentHTML(),
                success: function () {
                    if (me.type === 'edit') {
                        var userData = select[0];
                        me.editUserId = userData.userid;
                        var roleid = 0;
                        $.each(me.userRoleData, function (index, item) {
                            if (item.userid == userData.userid) {
                                roleid = item.roleid;
                                return false;
                            }
                        });
                        $('#user-roleid').val(roleid);
                        for (var key in userData) {
                            $('#user-' + key).val(userData[key]);
                        }
                    }
                    validate();
                },
                yes: function () {
                    $('#user-from .submit').trigger('click');
                }
            });
        });
    };
    (function () {
        init(getModalContentHTML, getUserRoles, validate);
    })();
}

modalFactory.prototype = {
    save: function () {
        var me = this;
        var p = {
            loginname: $("#user-loginname").val(),
            loginpassword: md5($("#user-loginpassword").val()),
            realname: $("#user-realname").val(),
            title: $("#user-title").val(),
            sex: $("#user-sex").val(),
            phone: $("#user-phone").val(),
            qq: $("#user-qq").val(),
            weixinid: $("#user-weixinid").val(),
            weixinname: $("#user-weixinname").val(),
            remark: $("#user-remark").val(),
            departmentid:$("#user-departmentid").val(),
            enabled: 1
        };
        var post = {
            user: p,
            roleid: $('#user-roleid').val()
        };
        $.post("../userManage/save", {data: JSON.stringify(post)}, function (data) {
            if (data === 'true') {
                layer.close(me.index);
                me.linkTable.loadData();
                layer.msg("添加成功！", {icon: 1});
            } else {
                layer.msg("添加失败！", {icon: 2});
            }
        });
    },
    update: function () {
        var me = this;
        var p = {
            userid: me.editUserId,
            loginname: $("#user-loginname").val(),
            realname: $("#user-realname").val(),
            title: $("#user-title").val(),
            sex: $("#user-sex").val(),
            phone: $("#user-phone").val(),
            qq: $("#user-qq").val(),
            weixinid: $("#user-weixinid").val(),
            weixinname: $("#user-weixinname").val(),
            remark: $("#user-remark").val(),
            departmentid:$("#user-departmentid").val()
        };
        var post = {
            user: p,
            roleid: $('#user-roleid').val()
        };
        $.post("../userManage/update", {data: JSON.stringify(post)}, function (data) {
            if (data === 'true') {
                layer.close(me.index);
                me.linkTable.loadData();
                layer.msg("修改成功！", {icon: 1});
            } else {
                layer.msg("修改失败！", {icon: 2});
            }
        });
    }
};

function addListeners (tableObj) {
    $('#btn-add').off('click');
    $('#btn-delete').off('click');
    $('#btn-edit').off('click');
    $('#btn-add').on('click', function () {
        new modalFactory('add', tableObj);
    });
    $('#btn-delete').on('click', function () {
        // tableObj.delete();
    });
    $('#btn-edit').on('click', function () {
        new modalFactory('edit', tableObj);
    });
}
